from rest_framework.response import Response
from api import models
from rest_framework.generics import ListAPIView
from api.authentication.auth import GeneralAuthentication, UserAuthentication
from api.serializer.comment import CommentModelSerializer, CreateCommentModelSerializer
from rest_framework import status
from django.db.models import F


class CommentView(ListAPIView):
    queryset = models.CommentRecord.objects
    serializer_class = CommentModelSerializer

    def get_authenticators(self):
        if self.request.method == "POST":
            return [UserAuthentication(), ]
        return [GeneralAuthentication(), ]

    def get_queryset(self):
        root_id = self.request.query_params.get('root_id')
        return self.queryset.filter(root_id=root_id)

    def post(self, request, *args, **kwargs):
        ser = CreateCommentModelSerializer(data=request.data)
        if ser.is_valid():
            token = request.data.get('token')
            news_id = request.data.get('news')
            user_object = models.UserInfo.objects.filter(token=token).first()
            ser.save(user=user_object)
            models.News.objects.filter(id=news_id).update(comment_count=F('comment_count') + 1)
            return Response(ser.data, status=status.HTTP_201_CREATED)
        return Response(ser.errors, status=status.HTTP_400_BAD_REQUEST)
